package org.edu.modules.base.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.edu.common.api.vo.Result;
import org.edu.common.aspect.annotation.AutoLog;
import org.edu.common.system.query.QueryGenerator;
import org.edu.common.system.vo.LoginUser;
import org.edu.modules.base.entity.PageBean;
import org.edu.modules.base.entity.SysLog;
import org.edu.modules.base.entity.VeBaseUserAccess;
import org.edu.modules.base.service.ISysLogService;
import org.edu.modules.base.service.IVeBaseUserAccessService;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

@Api(tags = {"日志管理"})
@RestController
@RequestMapping("/base/veLog")
@ApiSort(60)
public class VeLogController {
    private static final Logger log = LoggerFactory.getLogger(VeLogController.class);
    @Autowired
    private ISysLogService sysLogService;
    @Autowired
    private IVeBaseUserAccessService userAccessService;

    @AutoLog("系统日志-分页列表查询")
    @ApiOperation(value = "系统日志-分页列表查询", notes = "系统日志-分页列表查询")
    @GetMapping({"/querySysLogPageList"})
    public Result<?> querySysLogPageList(SysLog sysLog, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        int num = this.sysLogService.getSysLogAllList(sysLog);
        PageBean pb = new PageBean(pageNo.intValue(), pageSize.intValue(), num);
        sysLog.setStartIndex(Integer.valueOf(pb.getStartIndex()));
        sysLog.setPageSize(pageSize);
        pb.setList(this.sysLogService.getSysLogPageList(sysLog));
        return Result.ok(pb);
    }

    @AutoLog("错误日志-分页列表查询")
    @ApiOperation(value = "错误日志-分页列表查询", notes = "错误日志-分页列表查询")
    @GetMapping({"/ErrorUserAccessPageList"})
    public Result<?> ErrorUserAccessPageList(VeBaseUserAccess userAccess, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        int num = this.userAccessService.errorUserAccessAllList(userAccess);
        PageBean pb = new PageBean(pageNo.intValue(), pageSize.intValue(), num);
        userAccess.setStartIndex(Integer.valueOf(pb.getStartIndex()));
        userAccess.setPageSize(pageSize);
        pb.setList(this.userAccessService.errorUserAccessPageList(userAccess));
        return Result.ok(pb);
    }

    @AutoLog("访问日志-分页列表查询")
    @ApiOperation(value = "访问日志-分页列表查询", notes = "访问日志-分页列表查询")
    @GetMapping({"/UserAccessPageList"})
    public Result<?> UserAccessPageList(VeBaseUserAccess userAccess, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        int num = this.userAccessService.userAccessAllList(userAccess);
        PageBean pb = new PageBean(pageNo.intValue(), pageSize.intValue(), num);
        userAccess.setStartIndex(Integer.valueOf(pb.getStartIndex()));
        userAccess.setPageSize(pageSize);
        pb.setList(this.userAccessService.userAccessPageList(userAccess));
        return Result.ok(pb);
    }

    @AutoLog("访问统计")
    @ApiOperation(value = "访问统计", notes = "访问统计")
    @GetMapping({"/UserAccessStatistics"})
    public Result<?> UserAccessStatistics(String beginDate, String endDate) {
        List<Map<String, Object>> list = this.userAccessService.userAccessStatistics(beginDate, endDate);
        return Result.ok(list);
    }

    @AutoLog("通过id查询日志信息")
    @ApiOperation(value = "通过id查询日志信息", notes = "通过id查询日志信息")
    @GetMapping({"/ErrorUserAccessById"})
    public Result<?> ErrorUserAccessById(@RequestParam(name = "id", required = true) String id) {
        VeBaseUserAccess userAccess = (VeBaseUserAccess) this.userAccessService.getById(id);
        if (userAccess == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(userAccess);
    }

    @AutoLog("系统日志信息-添加")
    @ApiOperation(value = "系统日志信息-添加", notes = "系统日志信息-添加")
    @PostMapping({"/add"})
    public Result<?> add(@RequestBody VeBaseUserAccess userAccess) {
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        userAccess.setId(uuid);
        this.userAccessService.save(userAccess);
        return Result.ok("添加成功");
    }

    @AutoLog("系统日志信息-修改")
    @ApiOperation(value = "系统日志信息-修改", notes = "系统日志信息-修改")
    @PostMapping({"/edit"})
    public Result<?> edit(@RequestBody SysLog sysLog) {
        this.sysLogService.updateById(sysLog);
        return Result.ok("修改成功");
    }

    @AutoLog("系统日志信息-单个删除")
    @ApiOperation(value = "系统日志信息-单个删除", notes = "系统日志信息-单个删除")
    @PostMapping({"/delete"})
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        this.sysLogService.removeById(id);
        return Result.ok("删除成功");
    }

    @AutoLog("系统日志信息-批量删除")
    @ApiOperation(value = "系统日志信息-批量删除", notes = "系统日志信息-批量删除")
    @PostMapping({"/deleteBatch"})
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.sysLogService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功");
    }

    @RequestMapping("/exportXls")
    @ApiOperation(value = "系统日志-导出", notes = "导出excel")
    public ModelAndView exportXls(SysLog sysLog, HttpServletRequest request) {
        QueryWrapper<SysLog> queryWrapper = QueryGenerator.initQueryWrapper(sysLog, request.getParameterMap());

        ModelAndView modelAndView = new ModelAndView(new JeecgEntityExcelView());
        List<SysLog> pageList = this.sysLogService.list(queryWrapper);

        modelAndView.addObject("fileName", "系统日志信息");
        modelAndView.addObject("entity", SysLog.class);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        modelAndView.addObject("params", new ExportParams("系统日志列表", "导出人:" + user.getRealname(), "导出信息"));
        modelAndView.addObject("data", pageList);
        return modelAndView;
    }

    @ResponseBody
    @RequestMapping(value = {"uploadfile"}, produces = {"multipart/form-data;charset=UTF-8"})
    public String uploadfiles(HttpServletRequest request) {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            DefaultMultipartHttpServletRequest multipartRequest = (DefaultMultipartHttpServletRequest) request;
            MultipartFile multipartFile = multipartRequest.getFile("file");
            if (multipartFile == null) {
                System.out.println("文件为空!");
            }
            String filename = multipartRequest.getFile("file").getOriginalFilename();

            String tmpFile = request.getSession().getServletContext().getRealPath("/") + UUID.randomUUID().toString().replace("-", "") + ".apk";
            File targetFile = new File(tmpFile);
            if (null != multipartFile) {
                try {
                    multipartFile.transferTo(targetFile);
                } catch (IllegalStateException e) {
                    log.error(e.getMessage(), e);
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
        return "";
    }
}
